blog

home / developersection / blogs / c# strings: a complete guide for beginners

C# Strings: A Complete Guide for Beginners

C# Strings: A Complete Guide for Beginners

Anubhav Kumar 440 22-Apr-2025

C# Strings: A Complete Guide for Beginners

In C#, strings are used to store sequences of characters like names, sentences, file paths, and more. They are one of the most essential data types used in everyday programming.

What is a String?

In C#, a string is a collection of characters enclosed in double quotes ("). It’s part of the System.String class.

Example:

string greeting = "Hello, World!";
string empty = ""; // empty string

Key Points About C# Strings

  • Strings are immutable: once created, they cannot be changed.
  • All string operations return a new string.
  • string is an alias for System.String.

Common String Operations

1. Concatenation

Combining strings using the + operator.

string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName); // John Doe

2. String Interpolation

Easier way to combine variables with strings.

string name = "Alice";
int age = 25;
string info = $"Name: {name}, Age: {age}";

3. Common String Methods

Method Description Example
ToUpper() Converts to uppercase "hello".ToUpper()"HELLO"
ToLower() Converts to lowercase "HELLO".ToLower()"hello"
Contains("text") Checks if substring exists "welcome".Contains("come")true
Replace("a", "b") Replaces characters "car".Replace("c", "b")"bar"
Substring(0, 4) Extracts a portion of the string "Example".Substring(0, 4)"Exam"
Trim() Removes whitespace from both ends " hi ".Trim()"hi"
Split(' ') Splits string by character or word "one two".Split(' ')["one", "two"]
IndexOf("word") Returns index of first occurrence "hello".IndexOf("e")1

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/

 

Special String Types

Verbatim Strings (@)

Used for file paths or strings with escape characters.

string path = @"C:\Users\John\Documents";

Escape Sequences

Sequence Description
\n New line
\t Tab space
\\ Backslash
\" Double quote

Example - 

string message = "Hello\nWorld!";

String vs StringBuilder

Since strings are immutable, use StringBuilder for efficient modifications:

using System.Text;

StringBuilder sb = new StringBuilder("Hello");
sb.Append(" World");
Console.WriteLine(sb.ToString()); // Hello World

Summary

Feature Example
Declare a string string name = "Bob";
Combine strings "Hello" + " " + "World"
String interpolation $"Hi, {name}"
Access length name.Length
Modify with methods name.ToUpper(), name.Replace()
Use escape characters "Line1\nLine2"
Handle efficiently StringBuilder

c# c# 
Updated 22-Apr-2025
Anubhav Kumar

Student

The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .

Leave Comment

Comments

Liked By